package com.yanyeori.framework.web.http.request;

import com.yanyeori.framework.core.constant.BaseConstant;
import com.yanyeori.framework.core.context.TraceContext;
import com.yanyeori.framework.core.context.UserContext;
import com.yanyeori.framework.core.util.HttpUtil;
import com.yanyeori.framework.core.util.JacksonUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * http请求header通用处理
 *
 * @author chenkuan
 * @since 2021/8/3
 */
public class GeneralRequestHeader {

    /**
     * 重写该方法以提供自定义的Context实例数据
     *
     * @return 需要进行跨服务传递的对象实例数据
     */
    public Collection<Object> getContext() {
        //默认的Context处理
        return Stream.of(UserContext.get(), TraceContext.get(true)).collect(Collectors.toSet());
    }

    protected Map<String, String> contextsToHeadersMap(Collection<Object> contexts) {
        Map<String, String> headersMap = new HashMap<>();
        //获取所有待处理的context实例
        if (CollectionUtils.isNotEmpty(contexts)) {
            for (Object context : contexts) {
                if (context != null) {
                    Map<String, String> contextBeanToMap = contextBeanToMap(context);
                    if (!contextBeanToMap.isEmpty()) {
                        headersMap.putAll(contextBeanToMap);
                    }
                }
            }
        }
        return headersMap;
    }

    private <T> Map<String, String> contextBeanToMap(T bean) {
        Map<String, String> map = new HashMap<>();
        map.put(BaseConstant.HEADER_PRE + bean.getClass().getSimpleName(), HttpUtil.encodeUrl(JacksonUtil.toJson(bean)));
        return map;
    }
}
